<template>
  <div class="user-view">
    <el-table
      :header-cell-style="headerCellStyle"
      :cell-style="cellStyle"
      :data="tableData"
      style="width: 100%"
      :row-style="rowStyle"
      v-loading="loading"
      element-loading-text="拼命加载中"
      element-loading-spinner="el-icon-loading"
      element-loading-background="rgba(0, 0, 0)"
    >
      <el-table-column prop="id" label="ID"></el-table-column>
      <el-table-column
        prop="username"
        label="用户名"
        width="150"
      ></el-table-column>
      <el-table-column
        prop="name"
        label="真实姓名"
        width="150"
      ></el-table-column>
      <el-table-column prop="gender" label="性别"></el-table-column>
      <el-table-column prop="email" label="邮箱"></el-table-column>
      <el-table-column
        prop="birthday"
        label="出生日期"
        width="150"
        :formatter="formatDate"
      ></el-table-column>
      <el-table-column
        prop="phoneNumber"
        label="手机号"
        width="150"
      ></el-table-column>
      <el-table-column prop="role" label="角色"></el-table-column>
      <el-table-column label="操作" width="150">
        <template slot-scope="scope">
          <el-button
            type="primary"
            size="mini"
            @click="handleEdit(scope.$index, scope.row)"
            >编辑</el-button
          >
          <el-button
            type="danger"
            size="mini"
            @click="handleDelete(scope.$index, scope.row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <div>
      <el-dialog
        :z-index="2000"
        :visible.sync="editDialogVisible"
        title="编辑用户"
        :modal-append-to-body="false"
      >
        <el-form :model="editForm" ref="editForm" label-width="80px">
          <el-form-item label="ID">
            <el-input disabled v-model="editForm.id"></el-input>
          </el-form-item>
          <el-form-item label="真实姓名">
            <el-input v-model="editForm.name"></el-input>
          </el-form-item>
          <el-form-item label="性别">
            <el-input v-model="editForm.gender"></el-input>
          </el-form-item>
          <el-form-item label="邮箱">
            <el-input v-model="editForm.email"></el-input>
          </el-form-item>
          <el-form-item label="出生日期">
            <el-date-picker
              v-model="editForm.birthday"
              type="date"
              format="yyyy-MM-dd"
              value-format="timestamp"
              placeholder="选择日期"
            ></el-date-picker>
          </el-form-item>
          <el-form-item label="手机号">
            <el-input v-model="editForm.phoneNumber"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="submitEdit">保存</el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import request from "@/utils/request";

export default {
  data() {
    return {
      loading: true,
      user: {},
      headerCellStyle: {
        background: "#000034",
      },
      cellStyle: {
        background: "#032241",
      },
      rowStyle: {
        background: "#032241",
      },
      editDialogVisible: false,
      editForm: {
        id: null,
        name: null,
        gender: null,
        email: null,
        phoneNumber: null,
        birthday: null,
      },
    };
  },
  computed: {
    tableData() {
      return this.user.users;
    },
  },
  methods: {
    async fetchUser() {
      try {
        const res = await request({
          url: "/api/admins/users",
          method: "GET",
        });
        this.loading = false;
        this.user = res.data;
        console.log(this.user);
      } catch (error) {
        this.loading = false;
        this.$message.error("获取用户信息失败");
        console.error(error);
        return false;
      }
    },
    handleEdit(index, row) {
      let {
        id = null,
        name = null,
        gender = null,
        email = null,
        phoneNumber = null,
        birthday = null,
      } = row;
      birthday = birthday
        ? new Date(birthday).toISOString().substr(0, 10)
        : null;
      this.editForm = {
        id,
        name,
        gender,
        email,
        phoneNumber,
        birthday,
      };
      this.$nextTick(() => {
        this.editDialogVisible = true;
      });
    },
    async handleDelete(index, row) {
      try {
        await request({
          url: `/api/admins/users/${row.id}`,
          method: "DELETE",
        });
        this.$message.success("用户删除成功");
        // 删除本地数据中的用户
        this.user.users.splice(index, 1);
      } catch (error) {
        this.$message.error("删除用户失败");
        console.error(error);
      }
    },
    async submitEdit() {
      // 将 yyyy-mm-dd 转换为时间戳
      if (this.editForm.birthday) {
        this.editForm.birthday = new Date(this.editForm.birthday).getTime();
      }
      console.log(this.editForm);
      delete this.editForm.username;
      try {
        await request({
          url: `/api/admins/users`,
          method: "PATCH",
          data: this.editForm,
        });
        this.$message.success("用户信息更新成功");
        this.editDialogVisible = false;
        // 更新本地数据
        const userIndex = this.user.users.findIndex(
          (user) => user.id === this.editForm.id
        );
        if (userIndex !== -1) {
          this.$set(this.user.users, userIndex, { ...this.editForm });
        }
      } catch (error) {
        this.$message.error("更新用户信息失败");
        console.error(error);
      }
    },
    formatDate(row, column, cellValue, index) {
      return cellValue ? new Date(cellValue).toISOString().substr(0, 10) : "";
    },
  },
  async mounted() {
    await this.fetchUser();
  },
};
</script>
